#pragma once
#include <vector>
#include <string>
#include "icsearch.hpp"
#include "user.hxx"


class ESUser
{
    public:
    using ptr = std::shared_ptr<ESUser>;
    ESUser(const std::shared_ptr<elasticlient::Client>& es_client) :_es_client(es_client)
    {}

    bool createIndex() 
    {
        bool ret = ESIndex(_es_client,"user")
        .appendFields("user_id","keyword","standard",true)
        .appendFields("nickname")
        .appendFields("phone","keyword","standard",true)
        .appendFields("description","text","standard",false) 
        .appendFields("avatar_id","keyword","standard",false)
        .ceeateIndex();

        if(ret == false) {
            LOG_ERROR("用户信息检索失败");
            return false;
        }

        LOG_INFO("用户信息检索成功");

        return true;
    }

    bool appendData(const std::string& uid,
        const std::string &phone,
        const std::string& nickname,
        const std::string& description,
        const std::string& avatar_id)
    {
        bool ret = ESInsert(_es_client,"user")
        .appendFields("user_id",uid)
        .appendFields("nickname",nickname)
        .appendFields("phone",phone)
        .appendFields("description",description) 
        .appendFields("avatar_id",avatar_id)
        .insert(uid);

        if(ret == false) {
            LOG_ERROR("数据插入失败");
            return false;
        }

        LOG_INFO("数据插入成功");
        return true;
    }

    std::vector<User> search(const std::string &key, const std::vector<string> &uid_list)
    {
        std::vector<User> res;
        Json::Value json_user = ESSearch(_es_client, "user")
            .append_should_match("phone.keyword", key)
            .append_should_match("user_id.keyword", key)
            .append_should_match("nickname", key)
            .append_must_not_terms("user_id.keyword", uid_list)
            .search();

        if(json_user.isArray() == false) {
            LOG_ERROR("用户搜索结果为空，或者结果不是数组类型");
            return res;
        }

        int sz = json_user.size();
        for(int i =0; i<sz; i++) {
            User user;
            user.set_user_id(json_user[i]["_source"]["user_id"].asString());
            user.set_nickname(json_user[i]["_source"]["nickname"].asString());
            user.set_description(json_user[i]["_source"]["description"].asString());
            user.set_phone(json_user[i]["_source"]["phone"].asString());
            user.set_avatar_id(json_user[i]["_source"]["avatar_id"].asString());
            res.push_back(user);
        }

        return res;
    }

    private: 
    std::shared_ptr<elasticlient::Client> _es_client;
};
